package com.kaifamiao.www.demo.do0907;

import java.sql.*;

public class DBUtil implements AutoCloseable {
    /**
     * 1,注册驱动
     * 2，获取连接
     * 3，执行查询
     * 4，关闭连接
     */
    private static String driverClassName = "com.mysql.cj.jdbc.Driver";
    private String url;
    private String user;
    private String password;

    //连接
    private Connection conn;
    private PreparedStatement statement;
    private ResultSet set;
    static {
        registerDriver();
    }
    private static void registerDriver(){
        //不传参数时加载
        registerDriver(driverClassName);
    }
    public static void registerDriver(String driverClassName){
        try {
            Class.forName(driverClassName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.err.println("数据库注册驱动失败");
        }
    }
    public DBUtil(){}
    public DBUtil(String url){
     this.url = url;
    }
    public DBUtil(String url,String user,String password){
        this.url = url;
        this.user = user;
        this.password = password;
    }
    //封装连接过程
    public Connection getConnection() throws SQLException {
        if (user == null) {
            return getConnection(url);
        }else {
            return getConnection(this.url,this.user,this.password);
        }
    }
    public Connection getConnection(String url) throws SQLException {
       if (conn == null){
           conn = DriverManager.getConnection(url);
       }
        return conn;
    }
    public Connection getConnection(String url,String user,String password) throws SQLException {
        if (conn == null){
            conn = DriverManager.getConnection(url,user,password);
        }
       return conn;
    }


    @Override
    public void close() throws Exception {

    }
}
